package lifo.GammaTaf.SerieParallel;

import java.util.ArrayList;


import java.util.List;

import lifo.GammaTaf.SerieParallel.parsers.SerieParallelLexer;
import lifo.GammaTaf.SerieParallel.parsers.SerieParallelParser;

import org.antlr.runtime.ANTLRStringStream;
import org.antlr.runtime.CommonTokenStream;
import org.antlr.runtime.RecognitionException;
import org.antlr.runtime.TokenStream;
import org.antlr.runtime.tree.CommonTree;

public class SerieParallelCompiler {
	private List<RecognitionException> errors = new ArrayList<RecognitionException>();
	public SerieParallel compile(String expression) {
	    try {
	      //lexer splits input into tokens
	      ANTLRStringStream input = new ANTLRStringStream(expression);
	      SerieParallelLexer lexer= new SerieParallelLexer( input );
	      TokenStream tokens = new CommonTokenStream( lexer);
	      
	      //parser generates abstract syntax tree
	      SerieParallelParser parser = new SerieParallelParser(tokens);
	      SerieParallel sp = parser.expression();
	      
	      //collect all lexer errors
	      if (lexer.hasErrors())
	        errors.addAll(lexer.getAllErrors());
	     	   
	      //collect all parser errors
	      if (parser.hasErrors())
		        errors.addAll(parser.getAllErrors());

	      return sp;
	    } catch (RecognitionException e) {
	      throw new IllegalStateException("Recognition exception is never thrown, only declared.");
	  }

   }

	/**
	* @return all errors found during last run
	*/
	public List<RecognitionException> getAllErrors() {
	  return errors;
	}
	
	public static void printTree(CommonTree t, int indent) {
		   if ( t != null ) {
		      StringBuffer sb = new StringBuffer(indent);
		      for ( int i = 0; i < indent; i++ )
		        sb = sb.append("   ");
		     for ( int i = 0; i < t.getChildCount(); i++ ) {
		        System.out.println(sb.toString() + t.getChild(i).toString());
		        printTree((CommonTree)t.getChild(i), indent+1);
		     }
       }
	}

}